#!/bin/bash

# {{{1
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

## 检查是否安装了Graphviz的dot工具
#if ! command -v dot &> /dev/null; then
#    echo "Error: Graphviz is not installed. Please install Graphviz."
#    exit 1
#fi
# }}}

function print_call_tree {
	local function_name=$1
	local depth=$2
	local parent_function=$3
	local indent=$4

	# 使用cscope查询函数调用关系
	local call_tree=$(cscope -d -L -0 -c -3 "$function_name" | awk -F ' ' '{print $2}')
	# {{{1
	# 直接输出当前函数及其调用关系
	#    echo "  \"$parent_function\" -> \"$function_name\" [dir=back];" >> "$output_dot_filename.dot"
	#    echo -e "${indent}\033[0;3${depth}m|__>${NC}${function_name}"
	#}}}
	
	if [ "$depth" -lt 3 ]; then
		strlength=${#function_name}
		if [ $strlength -lt 30 ]; then
			padding=$(printf -- '-%.0s' $(seq 1 $((24 - strlength))))
			padding=$" ${padding}-^"
		else
			padding="-^"
		fi
	fi
	echo -e "${indent}${function_name}""$padding"

	# 递归地查询并输出子调用关系，直到达到指定深度
	if [ "$depth" -gt 0 ]; then
		# 递归地查询并输出子调用关系
		for call in $call_tree; do
			# 在自己调用自己的情况下，不进行递归
			if [ "$call" != "$function_name" ]; then
				print_call_tree "$call" $((depth - 1)) "$function_name" "${indent%???}"
			fi
		done
	fi
}

root_function="$1"
recursion_depth=3
# {{{1
## 接受用户输入的函数名和递归深度
#read -p "Enter the function name: " root_function
#read -p "Enter the recursion depth: " recursion_depth
#read -p "Enter the output DOT filename (without extension): " output_dot_filename
#
## 生成DOT文件头部
#echo "digraph CallGraph {" > "$output_dot_filename.dot"
#echo "  rankdir=RL;" >> "$output_dot_filename.dot"
# }}}
# 调用函数，开始输出调用关系树
print_call_tree "$root_function" "$recursion_depth" "$root_function" "									"

#{{{1
## 生成DOT文件尾部
#echo "}" >> "$output_dot_filename.dot"

## 使用dot工具生成PNG文件
#dot -Tpng -O "$output_dot_filename.dot"
#}}}
